package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    //提交预约信息
    @RequestMapping("/submit.do")
    public Result submit(Integer addressId, @RequestBody Map map, HttpServletResponse response){
        //获取电话号码
        String telephone = (String) map.get("telephone");
        //从redis集合获取电话号码
        Jedis resource = jedisPool.getResource();
        String redisValidateCode = resource.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        resource.close();
        //获取提交的验证码
        String validateCode = (String) map.get("validateCode");
        //比对验证码
        if(redisValidateCode != null && validateCode != null && validateCode.equals(redisValidateCode)){
            //对比成功 保存预约信息
            try{
                //调用业务层处理数据
                Result result = orderService.order(map,addressId);
                //保存用户信息到cookies
                //String md5Tele = MD5Utils.md5(telephone);
                Cookie cookie = new Cookie("member_telephone", telephone);
                cookie.setPath("/");
                cookie.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(cookie);
                return result;
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false, MessageConstant.ORDER_FAIL);
            }
        }else{
            //对比不成功
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }


    @RequestMapping("/findById.do")
    public Result findById(Integer id){
        try{
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
